package org.jeecg.modules.demo.zhidingyueduzhongdiangongzuo.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.modules.demo.zhidingyueduzhongdiangongzuo.entity.YueduzhongdianDto;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.zhidingyueduzhongdiangongzuo.entity.Yuedupeihebumen;
import org.jeecg.modules.demo.zhidingyueduzhongdiangongzuo.entity.Zhidingyueduzhongdiangongzuo;
import org.jeecg.modules.demo.zhidingyueduzhongdiangongzuo.vo.ZhidingyueduzhongdiangongzuoPage;
import org.jeecg.modules.demo.zhidingyueduzhongdiangongzuo.service.IZhidingyueduzhongdiangongzuoService;
import org.jeecg.modules.demo.zhidingyueduzhongdiangongzuo.service.IYuedupeihebumenService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;


 /**
 * @Description: 制定月度重点工作
 * @Author: jeecg-boot
 * @Date:   2025-11-07
 * @Version: V1.0
 */
@Tag(name="制定月度重点工作")
@RestController
@RequestMapping("/zhidingyueduzhongdiangongzuo/zhidingyueduzhongdiangongzuo")
@Slf4j
public class ZhidingyueduzhongdiangongzuoController {
	@Autowired
	private IZhidingyueduzhongdiangongzuoService zhidingyueduzhongdiangongzuoService;
	@Autowired
	private IYuedupeihebumenService yuedupeihebumenService;
	
	/**
	 * 分页列表查询
	 *
	 * @param zhidingyueduzhongdiangongzuo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "制定月度重点工作-分页列表查询")
//	@Operation(summary="制定月度重点工作-分页列表查询")
//	@GetMapping(value = "/list")
//	public Result<IPage<Zhidingyueduzhongdiangongzuo>> queryPageList(Zhidingyueduzhongdiangongzuo zhidingyueduzhongdiangongzuo,
//								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
//								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
//								   HttpServletRequest req) {
//        QueryWrapper<Zhidingyueduzhongdiangongzuo> queryWrapper = QueryGenerator.initQueryWrapper(zhidingyueduzhongdiangongzuo, req.getParameterMap());
//		Page<Zhidingyueduzhongdiangongzuo> page = new Page<Zhidingyueduzhongdiangongzuo>(pageNo, pageSize);
//		IPage<Zhidingyueduzhongdiangongzuo> pageList = zhidingyueduzhongdiangongzuoService.page(page, queryWrapper);
//		return Result.OK(pageList);
//	}
	 //制定页面接口List
	 @Operation(summary="制定月度重点工作-分页列表查询")
	 @GetMapping(value = "/list")
	 public Result<IPage<YueduzhongdianDto>> list(Zhidingyueduzhongdiangongzuo zhidingyueduzhongdiangongzuo,
												 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												 HttpServletRequest  req) {
		 //获取用户部门id
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 String departId = sysUser.getDepartIds();
		 //根据部门id查询自己负责部门的数据
		 QueryWrapper<Zhidingyueduzhongdiangongzuo> queryWrapper1 = new QueryWrapper<Zhidingyueduzhongdiangongzuo>();
		 queryWrapper1.eq("zhuguanbumen",departId);
		 Page<Zhidingyueduzhongdiangongzuo> page = new Page<Zhidingyueduzhongdiangongzuo>(pageNo, pageSize);
		 IPage<Zhidingyueduzhongdiangongzuo> pageList = zhidingyueduzhongdiangongzuoService.page(page, queryWrapper1);
		 List<Zhidingyueduzhongdiangongzuo> list = pageList.getRecords();
		 IPage<YueduzhongdianDto> pageDto = new Page<>();
		 List<YueduzhongdianDto> list1 = new ArrayList<>();
		 for(int i=0;i<list.size();i++){
			 YueduzhongdianDto yueduzhongdianDto = new YueduzhongdianDto();
			 BeanUtils.copyProperties(list.get(i),yueduzhongdianDto);
			 //插入配合部门
			 QueryWrapper<Yuedupeihebumen> queryWrapper3 = new QueryWrapper<Yuedupeihebumen>();
			 queryWrapper3.eq("zhidingid",list.get(i).getId());
			 List<Yuedupeihebumen> list3 = yuedupeihebumenService.list(queryWrapper3);
			 //遍历list3，拿出部门名称并拼接，再存入dto中
			 StringBuffer stringBuffer1 = new StringBuffer();
			 for(int j=0;j<list3.size();j++){
				 stringBuffer1.append(list3.get(j).getPeihebumen());
				 stringBuffer1.append(",");
			 }
			 yueduzhongdianDto.setPeihebumen(stringBuffer1.toString());
			 //插入驳回情况
			 QueryWrapper<Yuedupeihebumen> queryWrapper2 = new QueryWrapper<Yuedupeihebumen>();
			 queryWrapper2.eq("zhidingid",list.get(i).getId());
			 List<Yuedupeihebumen> list2 = yuedupeihebumenService.list(queryWrapper2);
			 //遍历list2，拿出状态为“已驳回”的部门名称并拼接，再存入dto中
			 StringBuffer stringBuffer2 = new StringBuffer();//创建一个可变的字符串对象，用来高效地进行字符串拼接或修改。
			 for(int j=0;j<list2.size();j++){
				 if(list2.get(j).getZhuangtai().equals("已驳回")){
					 stringBuffer2.append(list2.get(j).getPeihebumen());
					 stringBuffer2.append(",");
				 }
			 }
			 yueduzhongdianDto.setBohuiqingkuang(stringBuffer2.toString());
			 list1.add(yueduzhongdianDto);
		 }
		 pageDto.setRecords(list1);
		 return Result.OK(pageDto);
	 }

	 //列表页面接口
	 @GetMapping(value = "/liebiao")
	 public Result<IPage<YueduzhongdianDto>> liebiao(Zhidingyueduzhongdiangongzuo zhidingyueduzhongdiangongzuo,
												  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												  HttpServletRequest  req) {
		 //获取用户部门id
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 String departId = sysUser.getDepartIds();
		 //根据部门id查询自己负责部门的数据
		 QueryWrapper<Zhidingyueduzhongdiangongzuo> queryWrapper1 = new QueryWrapper<Zhidingyueduzhongdiangongzuo>();
		 Page<Zhidingyueduzhongdiangongzuo> page = new Page<Zhidingyueduzhongdiangongzuo>(pageNo, pageSize);
		 IPage<Zhidingyueduzhongdiangongzuo> pageList = zhidingyueduzhongdiangongzuoService.page(page, queryWrapper1);
		 List<Zhidingyueduzhongdiangongzuo> list = pageList.getRecords();
		 IPage<YueduzhongdianDto> pageDto = new Page<>();
		 List<YueduzhongdianDto> list1 = new ArrayList<>();
		 for(int i=0;i<list.size();i++){
			 YueduzhongdianDto yueduzhongdianDto = new YueduzhongdianDto();
			 BeanUtils.copyProperties(list.get(i),yueduzhongdianDto);
			 //插入主管配合
			 if(departId.equals(list.get(i).getZhuguanbumen())){
				 yueduzhongdianDto.setZhuguanpeihe("我主管的");
			 }else{
				 yueduzhongdianDto.setZhuguanpeihe("我配合的");
			 }
			 list1.add(yueduzhongdianDto);
		 }
		 pageDto.setRecords(list1);
		 return Result.OK(pageDto);
	 }


	/**
	 *   添加
	 *
	 * @param zhidingyueduzhongdiangongzuoPage
	 * @return
	 */
	@AutoLog(value = "制定月度重点工作-添加")
	@Operation(summary="制定月度重点工作-添加")
    @RequiresPermissions("zhidingyueduzhongdiangongzuo:z_zhidingyueduzhongdiangongzuo:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody ZhidingyueduzhongdiangongzuoPage zhidingyueduzhongdiangongzuoPage) {
		Zhidingyueduzhongdiangongzuo zhidingyueduzhongdiangongzuo = new Zhidingyueduzhongdiangongzuo();
		BeanUtils.copyProperties(zhidingyueduzhongdiangongzuoPage, zhidingyueduzhongdiangongzuo);
		//添加主管部门
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		zhidingyueduzhongdiangongzuo.setZhuguanbumen(sysUser.getDepartIds());
		zhidingyueduzhongdiangongzuo.setZhuangtai("进行中");
		zhidingyueduzhongdiangongzuoService.saveMain(zhidingyueduzhongdiangongzuo, zhidingyueduzhongdiangongzuoPage.getYuedupeihebumenList());
		return Result.OK("添加成功！");
	}


	 //选择责任主管
	 @GetMapping(value="/zerenzhuguanList")
	 public Result<List<SysUser>> zerenzhuguanList(){
		 List<SysUser> list =zhidingyueduzhongdiangongzuoService.getZerenzhuguanid();
		 return Result.OK(list);
	 }

	 //获取配合部门
	 @GetMapping(value="/peiheList")
	 public Result<List<SysDepart>> peiheList(){
		 List<SysDepart> list = zhidingyueduzhongdiangongzuoService.getPeihebumen();
		 return Result.OK(list);
	 }

	/**
	 *  编辑
	 *
	 * @param zhidingyueduzhongdiangongzuoPage
	 * @return
	 */
	@AutoLog(value = "制定月度重点工作-编辑")
	@Operation(summary="制定月度重点工作-编辑")
    @RequiresPermissions("zhidingyueduzhongdiangongzuo:z_zhidingyueduzhongdiangongzuo:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody ZhidingyueduzhongdiangongzuoPage zhidingyueduzhongdiangongzuoPage) {
		Zhidingyueduzhongdiangongzuo zhidingyueduzhongdiangongzuo = new Zhidingyueduzhongdiangongzuo();
		BeanUtils.copyProperties(zhidingyueduzhongdiangongzuoPage, zhidingyueduzhongdiangongzuo);
		Zhidingyueduzhongdiangongzuo zhidingyueduzhongdiangongzuoEntity = zhidingyueduzhongdiangongzuoService.getById(zhidingyueduzhongdiangongzuo.getId());
		if(zhidingyueduzhongdiangongzuoEntity==null) {
			return Result.error("未找到对应数据");
		}
		zhidingyueduzhongdiangongzuoService.updateMain(zhidingyueduzhongdiangongzuo, zhidingyueduzhongdiangongzuoPage.getYuedupeihebumenList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "制定月度重点工作-通过id删除")
	@Operation(summary="制定月度重点工作-通过id删除")
    @RequiresPermissions("zhidingyueduzhongdiangongzuo:z_zhidingyueduzhongdiangongzuo:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		zhidingyueduzhongdiangongzuoService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "制定月度重点工作-批量删除")
	@Operation(summary="制定月度重点工作-批量删除")
    @RequiresPermissions("zhidingyueduzhongdiangongzuo:z_zhidingyueduzhongdiangongzuo:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.zhidingyueduzhongdiangongzuoService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "制定月度重点工作-通过id查询")
	@Operation(summary="制定月度重点工作-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<Zhidingyueduzhongdiangongzuo> queryById(@RequestParam(name="id",required=true) String id) {
		Zhidingyueduzhongdiangongzuo zhidingyueduzhongdiangongzuo = zhidingyueduzhongdiangongzuoService.getById(id);
		if(zhidingyueduzhongdiangongzuo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(zhidingyueduzhongdiangongzuo);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "配合部门表通过主表ID查询")
	@Operation(summary="配合部门表主表ID查询")
	@GetMapping(value = "/queryYuedupeihebumenByMainId")
	public Result<List<Yuedupeihebumen>> queryYuedupeihebumenListByMainId(@RequestParam(name="id",required=true) String id) {
		List<Yuedupeihebumen> yuedupeihebumenList = yuedupeihebumenService.selectByMainId(id);
		return Result.OK(yuedupeihebumenList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param zhidingyueduzhongdiangongzuo
    */
    @RequiresPermissions("zhidingyueduzhongdiangongzuo:z_zhidingyueduzhongdiangongzuo:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Zhidingyueduzhongdiangongzuo zhidingyueduzhongdiangongzuo) {

      // Step.1 组装查询条件查询数据
      QueryWrapper<Zhidingyueduzhongdiangongzuo> queryWrapper = QueryGenerator.initQueryWrapper(zhidingyueduzhongdiangongzuo, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<Zhidingyueduzhongdiangongzuo> zhidingyueduzhongdiangongzuoList = zhidingyueduzhongdiangongzuoService.list(queryWrapper);

      // Step.3 组装pageList
      List<ZhidingyueduzhongdiangongzuoPage> pageList = new ArrayList<ZhidingyueduzhongdiangongzuoPage>();
      for (Zhidingyueduzhongdiangongzuo main : zhidingyueduzhongdiangongzuoList) {
          ZhidingyueduzhongdiangongzuoPage vo = new ZhidingyueduzhongdiangongzuoPage();
          BeanUtils.copyProperties(main, vo);
          List<Yuedupeihebumen> yuedupeihebumenList = yuedupeihebumenService.selectByMainId(main.getId());
          vo.setYuedupeihebumenList(yuedupeihebumenList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "制定月度重点工作列表");
      mv.addObject(NormalExcelConstants.CLASS, ZhidingyueduzhongdiangongzuoPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("制定月度重点工作数据", "导出人:"+sysUser.getRealname(), "制定月度重点工作"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("zhidingyueduzhongdiangongzuo:z_zhidingyueduzhongdiangongzuo:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<ZhidingyueduzhongdiangongzuoPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ZhidingyueduzhongdiangongzuoPage.class, params);
              for (ZhidingyueduzhongdiangongzuoPage page : list) {
                  Zhidingyueduzhongdiangongzuo po = new Zhidingyueduzhongdiangongzuo();
                  BeanUtils.copyProperties(page, po);
                  zhidingyueduzhongdiangongzuoService.saveMain(po, page.getYuedupeihebumenList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
